<template>
  <div class="article_list">
    <van-pull-refresh
      v-model="refreshing"
      @refresh="onRefresh"
      success-duration="1000"
      success-text="刷刷刷成功"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
      >
        <article-item
          v-for="item in list"
          :key="item.art_id"
          :title="item.title"
          :article="item"
        ></article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { articlesAPI } from "@/api";
import articleItem from "./article_item.vue";
export default {
  components: { articleItem },
  name: "List",
  props: {
    channels: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: null,
      refreshing: false,
      error: false,
    };
  },
  methods: {
    async onLoad() {
      // console.log(this.channels.id);
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      try {
        const res = await articlesAPI({
          channel_id: this.channels.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1,
        });
        this.list.push(...res.data.results);
        this.loading = false;
        if (res.data.pre_timestamp) {
          this.timestamp = res.data.pre_timestamp;
        } else {
          this.finished = true;
        }
      } catch (error) {
        this.loading = false;
        this.error = true;
      }
    },
    onRefresh() {
      // 清空列表数据
      this.list = [];
      this.finished = false;
      this.timestamp = null;

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.onLoad();
      this.loading = true;
      this.refreshing = false;
    },
  },
};
</script>

<style lang="less" scoped>
.article_list {
  height: calc(100vh - 188px);
  margin-top: 88px;
  overflow: auto;
}
</style>